import sys, math
import urllib2
from BeautifulSoup import BeautifulSoup


# Download the Key Statistics given a ticker symbol
# Return Key Statistics and list of Keys
def getKeyStats(ticker, DEBUG):
  # Download Key Stats from http://finance.yahoo.com/q/ks?s=MA

  # Open URL
  #  myURL='http://ichart.finance.yahoo.com/table.csv?'+\
  #                       's=%s&d=10&e=20&f=2010&g=d&a=9&b=20&c=2010'%t +\
  #                       '&ignore=.csv'

  myURL='http://finance.yahoo.com/q/ks?s=%s'%ticker

  if (DEBUG ):
      print myURL

  
    
  c=urllib2.urlopen(myURL)

  soup=BeautifulSoup(c.read())
  if DEBUG:
    print soup

  keyCount=0
  #StringToFind="EPS"
  key=""
  value=""
  keys={}
  keyStats={}
  for td in soup('td'):
  # Prints the heading
    if ('class' in dict(td.attrs) and td['class']=='yfnc_tablehead1'):
      key=td.text
      keys[keyCount]=key
      keyCount=keyCount + 1
      if DEBUG:
        print "*** Key is ***"
        print key
        
      continue
  # Prints the Value
    if ('class' in dict(td.attrs) and td['class']=='yfnc_tabledata1'):
        value=td.text
        if DEBUG:
          print "*** value = ***"
          print value
          
        keyStats[key]=value
        continue

  #for k in keyStats:
  #   print keyStats[k]

  #print keyStats["Diluted EPS (ttm):"]
  if DEBUG:
    print keyCount

  return keyStats, keyCount


def getValueFromKey( keyStats, key ):
  return keyStats[key]
  